/****************************************************************************
 **
 ** Trolltech hereby grants a license to use the Qt/Eclipse Integration
 ** plug-in (the software contained herein), in binary form, solely for the
 ** purpose of creating code to be used with Trolltech's Qt software.
 **
 ** Qt Designer is licensed under the terms of the GNU General Public
 ** License versions 2.0 and 3.0 ("GPL License"). Trolltech offers users the
 ** right to use certain no GPL licensed software under the terms of its GPL
 ** Exception version 1.2 (http://trolltech.com/products/qt/gplexception).
 **
 ** THIS SOFTWARE IS PROVIDED BY TROLLTECH AND ITS CONTRIBUTORS (IF ANY) "AS
 ** IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 ** TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 ** PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 ** OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 **
 ** Since we now have the GPL exception I think that the "special exception
 ** is no longer needed. The license text proposed above (other than the
 ** special exception portion of it) is the BSD license and we have added
 ** the BSD license as a permissible license under the exception.
 **
 ****************************************************************************/

#include "Mirror.h"
#include <QtGui>

const QSize DEFAULT_SIZE = QSize(640, 360);
const QRect MIRROR_SIZE = QRect(129, 37, 389, 292);

#define FILTER_PNG "*.PNG"

Mirror::Mirror(QWidget *parent) :
    QWidget(parent), camera(0), videoWidget(0)
{
    ui.setupUi(this);
    setupVideo();
    setupAbout();
    setupCamera();
    setupSettings();
    
    ui.listWidget->hide();    
}

Mirror::~Mirror()
{
    delete camera;
    delete videoWidget;
}

void Mirror::setupSettings()
{
    QDir dir(":/images/background", FILTER_PNG);
    QFileInfoList list = dir.entryInfoList( QDir::Files );
    for (int i = 0; i < list.size(); ++i) 
    {
        QIcon icon(list[i].absoluteFilePath());
        QListWidgetItem* item = new QListWidgetItem(icon, list[i].baseName(), ui.listWidget );   
    }   
    
    connect(ui.settingsButton, SIGNAL(toggled(bool)), this, SLOT(showSettings(bool)));
    connect(ui.listWidget,SIGNAL(itemClicked(QListWidgetItem*)), 
        this, SLOT(changeBackground(QListWidgetItem*)));
    connect(ui.listWidget,SIGNAL(doubleClicked(QListWidgetItem*)), 
        this, SLOT(changeBackgroundAndReturn(QListWidgetItem*)));
}

void Mirror::setupVideo()
{
    videoWidget = new QVideoWidget(ui.frame);
    videoWidget->setObjectName(QString::fromUtf8("videoWidget"));
    videoWidget->setGeometry(MIRROR_SIZE);
}

void Mirror::setupAbout()
{
    QPixmap pixmapAbout(":/images/about.png");
    about = new QAboutSplashScreen(this,pixmapAbout);  
    about->setGeometry(MIRROR_SIZE);
    connect( ui.aboutButton,SIGNAL(toggled(bool)),this,SLOT(showAbout(bool)));
    connect( about, SIGNAL(exitAbout()), this, SLOT(showAbout()));
}

void Mirror::showAbout(bool show)
{
    ui.aboutButton->setChecked(show);
    ui.settingsButton->setChecked(false);
    ui.listWidget->hide();
    if( show )
    {
        videoWidget->hide();
        about->show();
    }
    else
    {
        videoWidget->show();
        about->hide();
    }
}

void Mirror::showSettings(bool show)
{    
    ui.settingsButton->setChecked(show);
    ui.aboutButton->setChecked(false);
    about->hide();
    if( show )
    {
        videoWidget->hide();
        ui.listWidget->show();
    }
    else
    {
        videoWidget->show();
        ui.listWidget->hide();
    }
}

void Mirror::setupCamera()
{
    QByteArray cameraDevice = QCamera::availableDevices()[1];
    camera = new QCamera(cameraDevice);

    connect(camera, SIGNAL(error(QCamera::Error)), this, SLOT(error(QCamera::Error)));

    camera->setFocusMode(QCamera::AutoFocus);
//    camera->setMirrorEnabled( true );

    videoWidget->setMediaObject(camera);

    if (camera->state() == QCamera::ActiveState) {
        camera->stop();
    }
    camera->start();
}


void Mirror::changeBackground(QListWidgetItem* item)
{        
    QString baseName = item->text();
    QString style;
    QTextStream(&style) << "background-image: url(:/images/background/" << baseName << ".png);";
    ui.frame->setStyleSheet(
        QApplication::translate("Mirror", qPrintable(style), 0, QApplication::UnicodeUTF8));
    update();
}

void Mirror::changeBackgroundAndReturn(QListWidgetItem* item)
{
    changeBackground( item );
    showSettings( false );
}

void Mirror::error(QCamera::Error e)
{
    switch (e) {
    case QCamera::CameraError:
    {
        QMessageBox::warning(this, "Camera error", "General camera error");
        break;
    }
    case QCamera::NotReadyToCaptureError:
    {
        QMessageBox::warning(this, "Camera error", "Camera not ready to capture image");
        break;
    }
    case QCamera::InvalidRequestError:
    {
        QMessageBox::warning(this, "Camera error", "Invalid request");
        break;
    }
    case QCamera::ServiceMissingError:
    {
        QMessageBox::warning(this, "Camera error", "Service missing");
        break;
    }
    case QCamera::NotSupportedFeatureError:
    {
        QMessageBox::warning(this, "Camera error", "Not supported feature");
        break;
    }
    default:
        break;
    };
}
//void Mirror::paintEvent(QPaintEvent* evt)
//{
//    QPainter painter(this);
// 
//    if (!pixmap->isNull())
//        {
////        QPoint centerPoint(0,0);
////        // Scale new image which size is widgetSize
////        QPixmap scaledPixmap = pixmap->scaled(widgetSize, Qt::KeepAspectRatio);
////        // Calculate image center position into screen
////        centerPoint.setX((widgetSize.width()-scaledPixmap.width())/2);
////        centerPoint.setY((widgetSize.height()-scaledPixmap.height())/2);
//        // Draw image
//        painter.drawPixmap(QPoint(0,0),*pixmap);
//        }
//}



//void Mirror::setupBackground()
//{
//    //Using QPalette you can set background image as follows.
//    QPalette p = palette();
//    
//    QString privatePathQt(QDir::currentPath());
//    QString privatePathSymbian(QDir::toNativeSeparators(privatePathQt));
//    privatePathSymbian.append( "\\bg.PNG" );
//    //Load image to QPixmap, Give full path of image
//    QPixmap pixmap1(privatePathSymbian); //For emulator C: is ..\epoc32\winscw\c so image must be at that location
//
//    p.setBrush(QPalette::Background, pixmap1);
//    setPalette(p);
//}
